package com.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.managers.login.LoginManager;
import com.managers.session.SessionManager;

public class FilterAccess
        implements Filter {


    private FilterConfig filterConfig = null;



    public void init ( final FilterConfig fConfig )
            throws ServletException {

        this.filterConfig = fConfig;
    }



    @Override
    public void destroy () {

        //
    }



    public FilterConfig getFilterConfig () {

        return filterConfig;
    }



    public void setFilterConfig ( final FilterConfig filterConfig ) {

        this.filterConfig = filterConfig;
    }



    public void doFilter ( final ServletRequest request,
                           final ServletResponse response,
                           final FilterChain chain )
            throws IOException, ServletException {



        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final HttpServletResponse httpResponse = (HttpServletResponse) response;

        final LoginManager loginManager = LoginManager.sharedInstance();

        boolean isLoginFormDisplaying = loginManager.isLoginFormDisplaying();
        if ( !loginManager.hasClosedAllLoginForms() ) {
            if ( loginManager.isLoginGetMethodExecuted() ) {
                loginManager.resetLoginformOpenAttepts();
                loginManager.setLoginGetMethodExecuted(false);

            } else {
                isLoginFormDisplaying = false;
            }
        }

        boolean isValidUser = false;
        if ( !isLoginFormDisplaying ) {
            isValidUser = loginManager.isValidUser();
            if ( !isValidUser ) {
                final String userName = SessionManager.sharedInstance().cookieValue((HttpServletRequest) request, "userName");
                final String userPassword = SessionManager.sharedInstance().cookieValue((HttpServletRequest) request, "userPassword");
                isValidUser = loginManager.performUserCheck(userName, userPassword);
                if ( !isValidUser ) {
                    loginManager.doDefaultRedirection(httpRequest, httpResponse);
                }
            }
        }

        if ( isLoginFormDisplaying ) {
            chain.doFilter(request, response);
        } else {
            if ( isValidUser ) {
                chain.doFilter(request, response);
            }
        }
    }



}
